﻿using System;
using System.IO;
using System.Web;
using Cms.Application;
using Cms.Application.IO;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.Authentication;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;
using iLib.Web.UI;
using Page = System.Web.UI.Page;

namespace Cms.Web.UI
{
    public partial class PixlrCallbackHandler : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ProcessPixlrCallback();
            }
            catch (Exception ex)
            {
                Logging.LogError("PixlrCallbackHandler: " + ex.StackTrace + Environment.NewLine, ex);
            }
        }

        private void ProcessPixlrCallback()
        {
            IDiskAccess diskAccess = new DiskAccess();

            // Authenticate by checking if the userid string can be converted into an admin id
            AuthenticatedUser user = Conversion.ToAuthenticatedUser(Request.QueryString["userid"]);
            if (user.AdministratorID <= 0)
            {
                return;
            }
            IMediaRepository mr = new MediaRepository();
            IAdministratorRepository ar = new AdministratorRepository();
            ISiteRepository sr = new SiteRepository();
            Administrator administrator = ar.GetAdministrator(user.AdministratorID);

            // Get the existing file
            MediaFile mediaFile = mr.GetMediaFile(int.Parse(Request.QueryString["fileid"]));

            // Remove the existing file from the cache
            HttpContext.Current.Cache.Insert(mediaFile.GetVirtualPath(), "remove", null, DateTime.Now.AddDays(-1), TimeSpan.Zero);

            // Create the new filename with the extension from Pixlr
            string newName = mediaFile.Name;
            newName = newName.Substring(0, newName.LastIndexOf(".")) + "." + Request.QueryString["type"];

            // Get the existing file's location
            string folderPath = mediaFile.Folder != null
                                    ? mediaFile.Folder.GetPhysicalPath()
                                    : mediaFile.Site.RootMediaFolder;
            string url = Request.QueryString["image"];

            // For some reason, Pixlr returns urls like this:
            // http://pixlr.com/_temp/http://72.14.186.78/_temp/4e9dd3bef92ea111b7000005.jpg
            // This results in an exception when trying to save the file, so remove the first part, up until the last "http://"
            url = url.Substring(url.LastIndexOf("http://"));
            RemoteFileHandler.SaveRemoteFileToDisk(url, Url.PhysicalPath + folderPath + "\\" + newName + "$", true);

            // The new file got saved, delete the old one
            diskAccess.DeleteFile(mediaFile.GetPhysicalPath());

            // Remove the dollar sign from the new filename
            diskAccess.MoveFile(folderPath + "\\" + newName + "$", folderPath + "\\" + newName);
            var fileInfo = new FileInfo(Url.PhysicalPath + folderPath + "\\" + newName);
            mediaFile.Size = fileInfo.Length;
            mediaFile.UploadedTimestamp = DateTime.Now;
            mediaFile.Version = DateTime.Now.Ticks.ToString();
            mediaFile.Name = newName;
            administrator.CurrentSite.MediaFiles.Add(mediaFile);
            mr.SaveMediaFile(mediaFile);
            sr.SaveSite(administrator.CurrentSite);

            // Redirect back to Media
            string redirectUrl = Url.FullPath + "Admin/Media.aspx";
            if (!string.IsNullOrEmpty(Request.QueryString["browseitemdata"]))
            {
                redirectUrl += "?browseitemdata=" + Server.UrlEncode(Request.QueryString["browseitemdata"]);
            }
            Page.ClientScript.RegisterStartupScript(GetType(), "redirect", "parent.location.href = '" + redirectUrl + "';", true);
        }
    }
}